package com.sxkiler.demo.seata.service;

import com.sxkiler.demo.seata.dao.TCCProductDao;
import com.sxkiler.demo.seata.service.tcc.TCCProductService;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@org.apache.dubbo.config.annotation.Service
@Service
public class TCCProductServiceImpl implements TCCProductService {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private TCCProductDao productDao;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean productTry(BusinessActionContext actionContext, Long productId, Integer count) {
        String xId = actionContext.getXid();
        long branchId = actionContext.getBranchId();
        logger.info("[productTry]: 当前 XID:{}, branchId:{}, 商品:{}， 数量:{}", xId, branchId, productId, count);
        int flag = productDao.productTry(productId, count);

        if(flag == 0){
            throw new RuntimeException("库存服务 Try 阶段失败.");
        }

        logger.info("[productTry]: 冻结 {} 库存成功", count);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean productConfirm(BusinessActionContext actionContext) {
        String xId = actionContext.getXid();
        long branchId = actionContext.getBranchId();
        Integer productId = (Integer) actionContext.getActionContext("productId");
        Integer count = ((Integer) actionContext.getActionContext("count"));
        logger.info("[productConfirm]: 当前 XID:{}, branchId:{}, 商品:{}， 数量:{}", xId, branchId, productId, count);


        int flag = productDao.productConfirm(productId.longValue(), count);
        if(flag == 0){
            throw new RuntimeException("库存服务 Confirm 阶段失败.");
        }
        logger.info("[productConfirm]: 扣除 {} 库存成功", count);
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean productCancel(BusinessActionContext actionContext) {
        String xId = actionContext.getXid();
        long branchId = actionContext.getBranchId();
        Integer productId = ((Integer) actionContext.getActionContext("productId"));
        Integer count = ((Integer) actionContext.getActionContext("count"));
        logger.info("[productCancel]: 当前 XID:{}, branchId:{}, 商品:{}， 数量:{}", xId, branchId, productId, count);

        int flag = productDao.productCancel(productId.longValue(), count);
        if(flag == 0){
            throw new RuntimeException("库存服务 Cancel 阶段失败.");
        }
        logger.info("[productCancel]: 解除冻结 {} 库存成功", count);
        return true;
    }

    @Override
    public Integer getPriceById(Long productId) {
        return productDao.selectPriceById(productId);
    }
}
